﻿using System;
using System.Web;
using PmfWeb.Core.Utility;
using PmfWeb.Core.Cache;
using PmfWeb.Core.Web;

namespace PmfWeb.Core.HttpHandlers
{
    ///<summary>
    /// 重写执行类
    ///</summary>
    public class UrlRewriteModule : IHttpModule
    {
        #region 在线用户列表
        /// <summary>
        /// 在线列表
        /// </summary>
        public static Online<string, OnlineUser<string>> OnlineList = null;
        #endregion

        #region 管道初始化
        /// <summary>
        /// 管道初始化
        /// </summary>
        public void Init(HttpApplication context)
        {
            context.BeginRequest += rewrite_BeginRequest;
            context.AcquireRequestState += online_Request;
        }
        #endregion

        #region 在此统计在线
        /// <summary>
        /// 在此统计在线情况,获取请求状态事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void online_Request(object sender, EventArgs e)
        {
            if(null == OnlineList)
                OnlineList = Online<string, OnlineUser<string>>.Create(5);
            string name = Current.GetLoginName;
            string sessionID = Current.GetSessionID();
            bool isLogin = Current.IsLogin();
            
            if (isLogin)
            {
                if(!OnlineList.IsOnline(name))
                {
                    OnlineList.AddUser(name,new OnlineUser<string>());
                }
                else
                {
                    OnlineList.Update(name,Current.GetPageName());
                }
            }
            else
            {
                if(Utils.IsEmpty(sessionID)) return;
                if (!OnlineList.IsOnline(name))
                {
                    OnlineList.AddUser(sessionID,new OnlineUser<string>());
                }
                else
                {
                    OnlineList.Update(sessionID);
                }
            }
        }
        #endregion

        #region 开始重写
        private void rewrite_BeginRequest(object sender, EventArgs e)
        {
            HttpContext context = ((HttpApplication) sender).Context;
            string sPath = HttpContext.Current.Request.RawUrl;  //取得原始地址,去掉参数
            RewriteHelper helper = RewriteHelper.Instance();
            string result = helper.GetRewritePath(sPath);
            
            if (!System.String.IsNullOrEmpty(result) && context != null ) context.RewritePath(result);
        }
        #endregion

        #region 释放资源
        ///<summary>
        /// 释放资源
        ///</summary>
        public void Dispose()
        {
            OnlineList.Clear();
            OnlineList = null;
        }
        #endregion

    }
}
